<template>
  <div class="region-users-page">
    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <div class="text-base font-medium">区域成员</div>
          <div class="space-x-2">
            <el-button
              type="primary"
              :icon="useRenderIcon('ep:plus')"
              @click="openMemberDialog()"
            >
              添加成员
            </el-button>
            <el-button
              :icon="useRenderIcon('ep:refresh')"
              :loading="loading"
              @click="onSearch"
            >
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <el-form
        ref="formRef"
        :inline="true"
        :model="filterForm"
        class="search-form bg-bg_color w-full pl-4 pt-2 pb-2 overflow-auto"
      >
        <el-form-item label="区域" prop="region_id">
          <el-tree-select
            v-model="filterForm.region_id"
            :data="regionOptions"
            placeholder="全部区域"
            filterable
            clearable
            check-strictly
            :render-after-expand="false"
            :props="treeProps"
            class="w-[240px]!"
          />
        </el-form-item>
        <el-form-item label="用户ID" prop="user_id">
          <el-input
            v-model="filterForm.user_id"
            placeholder="用户ID"
            clearable
            class="w-[180px]!"
          />
        </el-form-item>
        <el-form-item label="角色" prop="role_type">
          <el-select
            v-model="filterForm.role_type"
            placeholder="全部角色"
            clearable
            class="w-[160px]!"
          >
            <el-option label="全部角色" value="" />
            <el-option
              v-for="item in roleOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="filterForm.status"
            placeholder="全部状态"
            clearable
            class="w-[140px]!"
          >
            <el-option label="全部状态" value="" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri:search-line')"
            :loading="loading"
            @click="onSearch"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon('ep:refresh')" @click="resetForm">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <PureTableBar
        title="区域成员列表"
        :columns="columns"
        :tableRef="tableRef"
        @refresh="onSearch"
        @fullscreen="tableRef.value?.setAdaptive?.()"
      >
        <template #default="{ size, dynamicColumns }">
          <template v-if="loading && dataList.length === 0">
            <el-skeleton :rows="12" animated />
          </template>
          <PureTable
            v-else
            ref="tableRef"
            v-loading="loading"
            row-key="id"
            :columns="dynamicColumns"
            :data="dataList"
            :size="size"
            :pagination="pagination"
            adaptive
            :adaptiveConfig="{ offsetBottom: 56 }"
            @page-current-change="handlePageChange"
            @page-size-change="handleSizeChange"
          >
            <template #status="{ row }">
              <el-tag
                :type="row.status === 1 ? 'success' : 'danger'"
                effect="plain"
                size="small"
              >
                {{ row.status === 1 ? "启用" : "禁用" }}
              </el-tag>
            </template>
            <template #is_primary="{ row }">
              <el-tag
                :type="row.is_primary === 1 ? 'warning' : 'info'"
                size="small"
              >
                {{ row.is_primary === 1 ? "主负责人" : "普通成员" }}
              </el-tag>
            </template>
            <template #operation="{ row }">
              <el-button
                link
                type="primary"
                :icon="useRenderIcon('ep:edit')"
                @click="openMemberDialog(row.id)"
              >
                编辑
              </el-button>
              <el-button
                link
                type="danger"
                :icon="useRenderIcon('ep:delete')"
                @click="removeMember(row.id)"
              >
                删除
              </el-button>
            </template>
          </PureTable>
        </template>
      </PureTableBar>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { PureTableBar } from "@/components/RePureTableBar";
import { useDialog } from "@/composables/useDialog";
import {
  fetchRegionTree,
  fetchRegionUserList,
  deleteRegionUser,
  REGION_USER_ROLE_OPTIONS,
  type RegionUserItem
} from "@/api/system/region/region";
import { useListPage } from "@/composables/useListPage";
import RegionUserForm from "./components/RegionUserForm.vue";

interface RegionNode {
  id: number;
  name: string;
  children?: RegionNode[];
}

interface RegionUserFilterForm {
  region_id: number | string;
  user_id: string;
  role_type: string;
  status: string | number;
}

const filterFormDefaults: RegionUserFilterForm = {
  region_id: "",
  user_id: "",
  role_type: "",
  status: ""
};

const treeProps = {
  label: "name",
  value: "id",
  children: "children"
};

const formRef = ref();
const tableRef = ref();
const regionOptions = ref<RegionNode[]>([]);
const { openDialog } = useDialog();

const {
  formState: filterForm,
  dataList,
  pagination,
  loading,
  onSearch,
  resetForm,
  handlePageChange,
  handleSizeChange
} = useListPage<RegionUserFilterForm, RegionUserItem>(
  {
    fetch: params =>
      fetchRegionUserList(
        params as RegionUserFilterForm & { page: number; page_size: number }
      )
  },
  filterFormDefaults,
  {},
  {
    paramsAdapter: params => {
      const adapted: Record<string, any> = { ...params };
      adapted.region_id = adapted.region_id
        ? Number(adapted.region_id)
        : undefined;
      adapted.user_id = adapted.user_id?.trim() || undefined;
      adapted.role_type = adapted.role_type || undefined;
      adapted.status = adapted.status === "" ? undefined : adapted.status;
      return adapted;
    },
    responseAdapter: response => ({
      list: response.list ?? [],
      total: response.pagination?.total ?? 0,
      pageSize: response.pagination?.pageSize ?? filterForm.page_size,
      currentPage: response.pagination?.currentPage ?? filterForm.page
    })
  }
);

const roleOptions = REGION_USER_ROLE_OPTIONS;

const columns: TableColumnList = [
  { type: "index", width: 60 },
  {
    label: "区域",
    prop: "region",
    minWidth: 200,
    formatter: (row: RegionUserItem) => row.region?.name ?? row.region_id
  },
  {
    label: "用户ID",
    prop: "user_id",
    minWidth: 120
  },
  {
    label: "角色",
    prop: "role_type",
    minWidth: 140,
    formatter: (row: RegionUserItem) =>
      roleOptions.find(item => item.value === row.role_type)?.label ??
      row.role_type
  },
  {
    label: "主负责人",
    prop: "is_primary",
    width: 140,
    slot: "is_primary"
  },
  {
    label: "状态",
    prop: "status",
    width: 120,
    slot: "status"
  },
  {
    label: "关联时间",
    prop: "create_time",
    minWidth: 180,
    formatter: (row: RegionUserItem) => row.create_time ?? "—"
  },
  {
    label: "更新时间",
    prop: "update_time",
    minWidth: 180,
    formatter: (row: RegionUserItem) => row.update_time ?? "—"
  },
  {
    label: "操作",
    width: 200,
    fixed: "right",
    slot: "operation"
  }
];

const loadRegionOptions = async () => {
  try {
    regionOptions.value = await fetchRegionTree();
  } catch (error: any) {
    ElMessage.error(error?.message ?? "加载区域树失败");
  }
};

const openMemberDialog = (id?: number) => {
  openDialog(RegionUserForm, {
    title: id ? "编辑区域成员" : "添加区域成员",
    width: "480px",
    props: {
      id: id ?? null,
      regionOptions: regionOptions.value
    },
    onConfirm: async (_: any, dialogProxy: any) => {
      if (dialogProxy?.submitForm) {
        const ok = await dialogProxy.submitForm();
        if (ok) {
          await onSearch();
        }
        return ok;
      }
      return true;
    }
  });
};

const removeMember = async (id: number) => {
  try {
    await ElMessageBox.confirm("确认删除该区域成员吗？", "删除成员", {
      type: "warning",
      confirmButtonText: "删除",
      cancelButtonText: "取消"
    });
  } catch {
    return;
  }

  try {
    await deleteRegionUser(id);
    ElMessage.success("区域成员已删除");
    await onSearch();
  } catch (error: any) {
    ElMessage.error(error?.message ?? "删除失败");
  }
};

loadRegionOptions();
onSearch();
</script>

<style scoped>
.region-users-page {
  display: flex;
  flex-direction: column;
  gap: 16px;
}
</style>
